import Cookies from 'js-cookie'

const setCookie = (key, value, time) => {
  Cookies.set(key, value, time)
}

const getCookie = (key) => {
  let val = Cookies.get(key)

  return val
}

const clearCookie = (key) => {
  Cookies.remove(key)
}

const formatDateTime = function (time, format) {
  if (isPlainObject(time)) time = time.getTime()

  var t = new Date(time)
  var tf = function (i) {
    return (i < 10 ? '0' : '') + i
  }
  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
    switch (a) {
      case 'yyyy':
        return tf(t.getFullYear())
        break
      case 'MM':
        return tf(t.getMonth() + 1)
        break
      case 'mm':
        return tf(t.getMinutes())
        break
      case 'dd':
        return tf(t.getDate())
        break
      case 'HH':
        return tf(t.getHours())
        break
      case 'ss':
        return tf(t.getSeconds())
        break
    }
  })
}

const download = function (url, flieType) {
  var elemIF = document.createElement('iframe')
  elemIF.src = baseUrl + url
  elemIF.style.display = 'none'
  document.body.appendChild(elemIF)
}

// 获得指定时间 @type day:当天 week:当周 moth:当月

// 补齐0
function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

// 获得本月天数
function getCountDays () {
  var curDate = new Date()
  var curMonth = curDate.getMonth()
  curDate.setMonth(curMonth + 1)
  curDate.setDate(0)
  return curDate.getDate()
}

// 获得上个月天数
function getPreDays () {
  var curDate = new Date()
  var curMonth = curDate.getMonth() - 1
  curDate.setMonth(curMonth + 1)
  curDate.setDate(0)
  return curDate.getDate()
}

export function formatDateType (type) {
  let newTime = new Date()
  let year = newTime.getFullYear()
  let month = newTime.getMonth() + 1
  let day = newTime.getDate()
  let nowDayOfWeek = newTime.getDay()

  let startDay = day - nowDayOfWeek
  let endDay = day + (6 - nowDayOfWeek)

  let startMoth = month
  let endMoth = month

  let startYear = year
  let endYear = year

  let transfromTime

  switch (type) {
    case 'day':
      transfromTime = {
        'beginDateStr': [year, month, day].map(formatNumber).join('-'),
        'endDateStr': [year, month, day].map(formatNumber).join('-')
      }
      break
    case 'week':
      if (endDay > getCountDays()) {
        endDay = endDay - getCountDays()
        endMoth = startMoth + 1
      }

      if (startDay < 0) {
        startDay = getPreDays() - Math.abs(day - nowDayOfWeek)
        startMoth = month - 1
        if (month == 1) {
          startYear = year - 1
          startMoth = '12'
        }
      }

      transfromTime = {
        'beginDateStr': [startYear, startMoth, startDay + 1].map(formatNumber).join('-'),
        'endDateStr': [endYear, endMoth, endDay + 1].map(formatNumber).join('-')
      }
      break
    case 'moth':
      startDay = '1'
      endDay = getCountDays()
      transfromTime = {
        'beginDateStr': [year, month, startDay].map(formatNumber).join('-'),
        'endDateStr': [year, month, endDay].map(formatNumber).join('-')
      }
      break
  }

  return transfromTime
}

/* 计算两个日期相差多少年
 * @startTime 开始时间
 * @endTime 结束时间
 */
export function diffYearBetweenDate (startTime, endTime) {
  startTime = new Date(startTime.replace(/-/g, '/'))
  endTime = new Date(endTime.replace(/-/g, '/'))

  const startYear = startTime.getFullYear()
  const startMonth = startTime.getMonth() + 1
  const startDay = startTime.getDate()

  const endYear = endTime.getFullYear()
  const endMonth = endTime.getMonth() + 1
  const endDay = endTime.getDate()

  const year = endYear - startYear
  const month = endMonth - startMonth
  const day = endDay - startDay

  if (month) {
    return `${year}.${month}`
  } else {
    return `${year}`
  }
}

const deepClone = function (arr) {
  var obj = arr.constructor == Array ? [] : {}

  for (var item in arr) {
    if (typeof arr[item] === 'object') {
      obj[item] = deepClone(arr[item])
    } else {
      obj[item] = arr[item]
    }
  }
  return obj
}

const Array = [].prototype = {
  insert (index, item) {
    this.splice(index, 0, item)
  }
}

function isPlainObject (obj) {
  return Object.prototype.toString.apply(obj) === '[object Object]'
}
/*
 *
 * 序列化对象
 *@url 打开地址
 *@obj 参数对象
 *@return 完整地址
 */
export function serialize (url, obj) {
  if (!isPlainObject(obj)) return
  Object.keys(obj).forEach(key => {
    let serializedParams = `${key}=${obj[key]}`

    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
  })
  return url
}

/* 函数节流 */
export function throttle (fn, interval) {
  var enterTime = 0// 触发的时间
  var gapTime = interval || 300 // 间隔时间，如果interval不传，则默认300ms
  return function () {
    var context = this
    var backTime = new Date()// 第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context, arguments)
      enterTime = backTime// 赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  }
}

/* 函数防抖 */
export function debounce (fn, interval) {
  var timer
  var gapTime = interval || 1000// 间隔时间，如果interval不传，则默认1000ms
  return function () {
    clearTimeout(timer)
    var context = this
    var args = arguments// 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function () {
      fn.call(context, args)
    }, gapTime)
  }
}

export default {
  formatDateTime,
  formatDateType,
  download,
  setCookie,
  getCookie,
  clearCookie,
  deepClone,
  Array,
  diffYearBetweenDate,
  serialize,
  throttle,
  debounce
}
